use lettre::smtp::response::Response;
use lettre::{
    smtp::authentication::Credentials, ClientSecurity, ClientTlsParameters, SmtpClient, Transport,
};
use lettre_email::Email;
use native_tls::TlsConnector;
use once_cell::sync::OnceCell;
use rand::Rng;

static HOST: OnceCell<String> = OnceCell::new();
static PORT: OnceCell<String> = OnceCell::new();
static USER: OnceCell<String> = OnceCell::new();
static PASSWD: OnceCell<String> = OnceCell::new();

pub fn init_email(host: String, port: String, user: String, pswd: String) {
    HOST.set(host.clone()).expect("验证host错误");
    PORT.set(port.clone()).expect("验证port错误");
    USER.set(user.clone()).expect("验证user错误");
    PASSWD.set(pswd.clone()).expect("验证passwd错误");
    log_info_ln!("邮箱设置完成,host:{},port:{},user:{},passwd:{}",host,port,user,pswd)
}

#[allow(unused_assignments)]
pub fn send_vali_code(email: String) -> Result<String, String> {
    let mut host = "-".to_string();
    let mut port = "-".to_string();
    let mut user = "-".to_string();
    let mut passwd = "-".to_string();
    let code = get_code();
    let body = format!(
        "<h1>这是聊天室注册的验证码 {} ，请妥善保管<h1>",
        code.clone()
    );
    if let Some(s) = HOST.get() {
        host = s.clone();
    } else {
        return Err("".to_string());
    }
    if let Some(s) = PORT.get() {
        port = s.clone();
    } else {
        return Err("".to_string());
    }
    if let Some(s) = USER.get() {
        user = s.clone();
    } else {
        return Err("".to_string());
    }
    if let Some(s) = PASSWD.get() {
        passwd = s.clone();
    } else {
        return Err("".to_string());
    }
    match send_mail(
        email,
        "验证邮件".to_string(),
        body,
        port,
        host,
        passwd,
        user,
    ) {
        Err(e) => Err(format!("验证发送错误:{}", e)),
        Ok(msg) => {
            if msg.code.to_string() == "200".to_string() ||  msg.code.to_string() == "250".to_string() {
                Ok(code)
            } else {
                Err(format!("code:{} message:{:?}", msg.code, msg.message))
            }
        }
    }
}

fn send_mail(
    to_addr: String,
    subject: String,
    body: String,
    smtp_port: String,
    smtp_host: String,
    smtp_passwd: String,
    smtp_user: String,
) -> Result<Response, String> {
    let mail = Email::builder()
        .to(to_addr)
        .from("1443965173@qq.com")
        .subject(subject)
        .html(&body)
        .build().expect("新建mail错误");

    let creds = Credentials::new(smtp_user, smtp_passwd);

    let addr = String::from(format!("{}:{}", smtp_host, smtp_port));
    let connector = TlsConnector::new().unwrap();
    let tls_params = ClientTlsParameters::new(smtp_host, connector);
    let security = ClientSecurity::Required(tls_params);
    let mut mailer = match SmtpClient::new(addr, security) {
        Ok(v) => v.credentials(creds).transport(),
        Err(e) => {
            return Err(format!(
                "Connecting to SMTP server was error: {}",
                e.to_string()
            ));
        }
    };

    match mailer.send(mail.into()) {
        Ok(resp) => Ok(resp),
        Err(e) => Err(e.to_string()),
    }
}

fn get_code() -> String {
    let r = rand::thread_rng().gen_range(1, 999999);
    format!("{:06}", r)
}

#[test]
fn test_get_code() {
    println!("获取一个随机数 {}", get_code());
}

#[test]
fn test() {
    match send_mail(
        "dong.wang@hex-tech.net".to_string(),
        "this is a subject".to_string(),
        "this is a body".to_string(),
        "25".to_string(),
        "smtp.qq.com".to_string(),
        "makjdmqsyhzfgjfc".to_string(),
        "1443965173@qq.com".to_string(),
    ) {
        Err(e) => println!("发送失败{}", e),
        Ok(msg) => println!("发送成功"),
    }
}
